import re
import requests
from mirai import Mirai,WebSocketAdapter,FriendMessage

HOST="127.0.0.1:8989"

def register(openid,qq):
    try:
        print("register:",openid,qq)
        url="http://"+HOST+"/register?openid="+openid+"&qq={0}".format(qq)
        res=requests.get(url)
        return res.text
    except Exception as e:
        print(e)
        return "操作失败"

def unbinding(qq):
    try:
        print("unbinding:",qq)
        url="http://"+HOST+"/unbinding?qq={0}".format(qq)
        res=requests.get(url)
        return res.text
    except Exception as e:
        print(e)
        return "操作失败"

if __name__=='__main__':
    bot =Mirai(
        qq=1438710740,
        adapter=WebSocketAdapter(
            verify_key='yirimirai',host='localhost',port=8080
        )
    )

    @bot.on(FriendMessage)
    def on_friend_message(event: FriendMessage):
        if str(event.message_chain)=='你好':
            return bot.send(event,'[机器人]此号现在正由机器人接管')
        else:
            openid=re.findall(r'#id{[-_\d\w]{28}}',str(event.message_chain))
            if len(openid)>0:
                return bot.send(event,register(openid[0].replace("#id{","").replace("}",""),event.sender.id) )
            elif re.match('#unbinding',str(event.message_chain)):
                return bot.send(event,unbinding(event.sender.id))
            else:
                return bot.send(event,"[机器人]请扫码进入小程序投稿:")
    
    bot.run()